import { AbstractCanvas } from './AbstractCanvas'

export default class GridCanvas extends AbstractCanvas {
  constructor(
    private canvas: HTMLCanvasElement,
    ctx: CanvasRenderingContext2D,
    private width: number,
    private height: number,
    private startY: number,
    private margin: number,
    private endX: number,
    private endY: number,
  ) {
    super(ctx)
    this.init()
  }

  // 初始化
  private init() {
    this.canvas.width = this.width
    this.canvas.height = this.height
    this.ctx.translate(this.margin, this.height - this.margin)
    // this.ctx.translate(0, this.startY)
    this.ctx.scale(1, -1)
  }

  /**
   * 绘制网格
   */
  public draw() {
    const step = 20
    const start = 0

    // 绘制横向的直线
    let y = 0
    while (y <= this.endY - this.startY) {
      if (y === 0 || y === this.endY - this.startY) {
        super.drawline([start, y], [this.endX, y], 0.5, 'black')
      } else {
        super.drawline([start, y], [this.endX, y], 0.2, '#7f8c8d')
      }
      y += step
    }

    // 绘制竖向的直线
    let x = start
    while (x <= this.endX) {
      if (x === 0 || x === this.endX) {
        super.drawline([x, start], [x, this.endY - this.startY], 0.5, 'black')
      } else {
        super.drawline([x, start], [x, this.endY - this.startY], 0.2, '#7f8c8d')
      }
      x += step
    }

    // 绘制纵向的数字
    y = start
    let txt = this.startY
    while (txt <= this.endY) {
      super.drawline([-3, y], [3, y], 3, '#000')
      super.drawline([this.endX - 3, y], [this.endX + 3, y], 3, '#000')

      this.ctx.save()
      this.ctx.scale(1, -1)
      super.drawText((txt / 2).toString(), [-15, -y], '#000')
      super.drawText((txt / 2).toString(), [this.endX + 15, -y], '#000')
      this.ctx.restore()

      y += step * 2
      txt += step * 2
    }
  }
}
